package com.hlkj.pay.app.merchant.ext.impl.huifu.utils;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import com.alibaba.fastjson.JSONObject;
import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.pay.app.merchant.ext.impl.huifu.constant.HuiFuConstant;
import com.huifu.bspay.sdk.opps.client.BasePayClient;
import com.huifu.bspay.sdk.opps.core.request.V2SupplementaryPictureRequest;
import com.huifu.bspay.sdk.opps.core.utils.DateTools;
import com.huifu.bspay.sdk.opps.core.utils.SequenceTools;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.core.utils.StringPool;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
/**
 * @author HlpayTeam
 * @date 2024/10/16 17:56
 */
@Slf4j
public class HuiFuUtil {
	/**
	 * 文件上传
	 *
	 * @param fileUrl
	 * @param fileType
	 * @return
	 * @throws Exception
	 */
	public static CommonResult<String> fileUpload(String fileUrl,String fileName, String fileType) {
		if (!file(fileUrl)) {
			log.info("文件格式错误 跳过文件上传:fileUrl:{},fileType:{}", fileUrl, fileType);
			return CommonResult.success();
		}
		// 1. 数据初始化
		// MerConfig merConfig = HuiFuMerchantAccessCompanyParamsHandle.merConfig(huiFuConfig);
		// BasePay.initWithMerConfig(merConfig);
		// 2.组装请求参数
		V2SupplementaryPictureRequest request = new V2SupplementaryPictureRequest();
		// 业务请求流水号
		request.setReqSeqId(SequenceTools.getReqSeqId32());
		// 业务请求日期
		request.setReqDate(DateTools.getCurrentDateYYYYMMDD());
		// 图片类型
		request.setFileType(fileType);
		// 图片名称
		request.setPicture(fileUrl.substring(fileUrl.lastIndexOf(StringPool.SLASH)+1));
		String[] split = request.getPicture().split("\\.");
		File tempFile = null;
		try {
			if(!StringUtils.hasText(fileName)){
				fileName=split[0];
			}
			tempFile = File.createTempFile(fileName, "."+ split[1]);
			URL url = new URL(fileUrl);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			connection.connect();
			// File file = new File(connection.getInputStream());
			// 创建临时文件
			// 将输入流复制到临时文件中
			try (OutputStream outputStream = new FileOutputStream(tempFile)) {
				byte[] buffer = new byte[1024];
				int bytesRead;
				while ((bytesRead = connection.getInputStream().read(buffer)) != -1) {
					outputStream.write(buffer, 0, bytesRead);
				}
			}
			Map<String, Object> response = BasePayClient.upload(request, tempFile);
			// System.out.println("返回数据:" + JSONObject.toJSONString(response));
			Object dataValue = response.get("data");
			if (dataValue == null) {
				log.warn("汇付文件上传失败,返回数据:{}", JSONObject.toJSONString(response));
				return CommonResult.error(HuiFuConstant.err_code, JSONObject.toJSONString(response));
			}
			cn.hutool.json.JSONObject jsonObject = JsonUtils.parseObj(dataValue.toString());
			cn.hutool.json.JSONObject data = jsonObject.getJSONObject("data");
			if (data == null) {
				log.warn("汇付文件上传失败,返回数据:{}", jsonObject.get("resp_desc"));
				return CommonResult.error(HuiFuConstant.err_code, jsonObject.get("resp_desc").toString());
			}
			Object fileId = data.get("file_id");
			if (fileId == null) {
				log.warn("汇付文件上传失败,返回数据:{}", jsonObject.get("resp_desc"));
				return CommonResult.error(HuiFuConstant.err_code, jsonObject.get("resp_desc").toString());
			}
			return CommonResult.success(fileId.toString());
		}
		catch (Exception e) {
			e.printStackTrace();
			return CommonResult.error(HuiFuConstant.err_code, e.getMessage());
		}
		finally {
			if (tempFile.exists()) {
				tempFile.delete();
			}
		}
	}
	public static String date(String date) {
		if (!StringUtils.hasText(date)) {
			return null;
		}
		return date.replace(StringPool.DASH, StringPool.EMPTY);
	}
	public static boolean file(String fileUrl) {
		if (!StringUtils.hasText(fileUrl)) {
			return false;
		}
		int indexOf = fileUrl.lastIndexOf(StringPool.SLASH);
		if (indexOf < 0) {
			return false;
		}
		String fileType = fileUrl.substring(indexOf);
		if (!fileType.contains(StringPool.DOT)) {
			return false;
		}
		return true;
	}
}
